const Controller = require('egg').Controller;

class CommonController extends Controller {

	async getFun () {


		const { ctx , app } = this;

		const fun = ctx.query.f;

		let sqlinfo = await app.redis.get('system').hget('dlq_sql', fun);

		console.log('sqlinfo');
		console.log(sqlinfo);

		if(sqlinfo == null){
			sqlinfo = await ctx.service.common.sqlToRedis(fun);
		}

		const sqlobj = JSON.parse(sqlinfo);

		console.log(sqlobj);

		


		const sqlArr = sqlobj.sqlstr.split('\n');
		const paramArr = JSON.parse(sqlobj.param);

		console.log(sqlArr);
		console.log(paramArr);

		//检测参数是否完整
		if(typeof paramArr == 'Array'){
			for(let i = 0; i < paramArr.length; i++){
				let item = paramArr[i];
				if(item.need && ctx.query[item.value] == undefined){
					ctx.helper.error(222, item.value + ' 是必传参数');
					return;
				}
			}
		}
		

		

		let index = 0;
		let resSQL = '';
		let newArr = [];

		sqlArr.forEach(str => {
			//如果是条件的话，
			if(str.indexOf('?') >= 0){
				if(ctx.query[paramArr[index].value] != undefined){
					resSQL += str + ' ';
					newArr.push(ctx.query[paramArr[index].value]);
				}
				index++;
			}else{
				resSQL += str + ' ';
			}
		})

		console.log(resSQL);


		//判断是什么操作
		const what = ctx.helper.trim(sqlobj.sqlstr).split(' ')[0].toLowerCase();
		//分页
		const pageNo = ctx.query.pageNo == undefined ? '' : ctx.query.pageNo;
		const pageSize = ctx.query.pageSize == undefined ? '' : ctx.query.pageSize;

		let pageSql = '';

		if(what == 'select'){
			if(pageNo != '' && pageSize != ''){
				let arr1 = resSQL.split('from');
				pageSql = 'select count(1) as totalRecord ';
				for(let i = 1; i < arr1.length; i++){
					pageSql += ' from ' + arr1[i];
				}
			}
		}

		const result = await ctx.service.common.getFun({
			sql : resSQL,
			arr : newArr,
			dbname : sqlobj.dbname,
			pageSql,
			pageSize,
			pageNo,
		});

		ctx.helper.success(result);

		// const what = sqlobj.sqlstr.split(' ')[0];

		// let res = null;

		// switch(what){
		// 	case 'select' :
		// 		res = this.selectOpt(sqlobj, ctx);
		// 		const result = await ctx.service.common.getFun(res);
		// 		ctx.helper.success(result);
		// 		break;
		// 	case 'insert' :
		// 		res = this.insertOpt(sqlobj, ctx);
		// 		//const result = await ctx.service.common.getFun(res);
		// 		ctx.helper.success(res);
		// 		break;
		// 	case 'update' :
		// 		break;
		// 	case 'delete' :
		// 		break;
		// 	default :

		// 	break;
		// }




		
	}

	/*
	 * 检测sql语句，将不合理的语法去掉
	 * 1.select * from aaa where aa=1 and => 把多余的and去掉
	 * 2.update abc set aa=1 , => 把多余的 , 去掉
	 * 3.select * from aaa where 把多余的where去掉
	 * 
	*/
	checkSQL (sql){
		let str = sql;

		// const aaa = [
		// 	{
		// 		value : 'username',
		// 	},
		// 	{
		// 		value : 'username',
		// 	},
		// 	{
		// 		value : 'id',
		// 		need : true,
		// 	},
		// ];

		console.log(JSON.stringify(aaa));

		return str;
	}



	selectOpt (sqlobj, ctx) {

		const { pageNo, pageSize } = ctx.query;

		//解析sql，获取查询条件。然后重新组合sql。
		const sql_arr = sqlobj.sqlstr.split('where');

		//console.log(sql_arr);
		//查询主体
		let sql_before = sql_arr[0];


		//查询条件
		let sql_condition = '';
		let condition = ' ';
		let newKeys = [];
		let arr = [];
		//有条件
		if(sql_arr.length > 1){
			sql_condition = sql_arr[1];

			console.log('sql_condition');
			console.log(sql_condition);

			//解析所有的条件
			let reg = new RegExp(/\s(\S*)=\?/g);
			let paras = sql_condition.match(reg);

			console.log(paras);

			let keys = [];
			paras.forEach(item => {
				keys.push(ctx.helper.trim(item).split('=?')[0]);
			})
			
			//通过传入的参数，去除其他的条件。
			//console.log(keys);
			keys.forEach((key, index) => {
				const t = ctx.query[key];
				if(t != undefined){
					newKeys.push(key);
					arr.push(t);
				}
			});

			//重新组装sql
			newKeys.forEach((key, index) => {
				if(index == newKeys.length - 1){
					condition += key + '=?';
				}else{
					condition += key + '=? and ';
				}
			});

			if(newKeys.length > 0){
				condition = ' where ' + condition;
			}

		}


		//条件后面的语句
		const sql_arr1 = sqlobj.sqlstr.split('=?');
		let sql_after = '';
		if(sql_arr1.length > 1){
			sql_after = sql_arr1[sql_arr1.length - 1];
		}

		const sql = sql_before + condition + sql_after
		//console.log(sql);

		//分页
		let sql_before_num = '';
		let pageSql = '';
		if(pageNo != undefined && pageSize != undefined){
			let before_arr = sql_before.split(' from ');
			sql_before_num = 'select count(1) as totalRecord from ' + before_arr[1];
			pageSql = sql_before_num + condition + sql_after;
		}


		return {
			dbname : sqlobj.dbname,
			sql,
			arr,
			pageSql,
			pageSize : parseInt(pageSize),
			pageNo : parseInt(pageNo),
		}

		// const result = await ctx.service.common.getFun(sqlobj.dbname, sql, arr, pageSql, parseInt(pageSize), parseInt(pageNo));
		// ctx.helper.success(result);
	}



	insertOpt (sqlobj, ctx) {

		return '1';
	}

	async setSqlToRedis () {

		const { ctx , app } = this;

		const name = ctx.query.name;

		console.log(name);

		const result = await ctx.service.common.sqlToRedis(name);


		console.log(result);

		ctx.helper.success(result);
	}



	async getTokenFromJuyou () {

		const { ctx , app } = this;

		console.log('getTokenFromJuyou');

		const { wxid } = ctx.query;

		const result = await ctx.curl('https://tsv.juyouhx.com/api/uc/wc/accountService/getToken', {
                method: 'GET',
                contentType: 'json',
                data: {
                    wxid,
                },
                dataType: 'json',
        });

        console.log(result);

        ctx.helper.success(result.data.data);

	}
    
}
module.exports = CommonController;